extern crate rustphp_parser;

use super::jit_interface::RustPhpJitInterface;
use rustphp_parser::rustphp::RustPhpParser;

pub struct VirtualMachine {}

impl VirtualMachine {
    pub fn new() -> VirtualMachine {
        let vm = VirtualMachine {};

        vm
    }

    /// 运行脚本
    pub fn run_script(&self, script: &str) {
        match RustPhpParser::new().parse(script) {
            Ok(result) => {
                let mut jit = RustPhpJitInterface::new();

                // 执行编译过程
                let main_function = jit.compile(result).unwrap();

                // 把*const u8指针转换成函数指针
                let main_function =
                    unsafe { std::mem::transmute::<_, fn() -> isize>(main_function) };

                // 执行JIT编译后的机器码
                main_function();
            }
            Err(e) => println!("{:?}", e),
        }
        println!();
    }
}
